#!/usr/bin/perl -w 

### Notes:
# The -T for security check would help to protect the script but was giving error and was removed.
# The arguments been used as parameterson external commands/scripts. For the arguments only hexadecimal and - are allowed. Feel free ADD extra protectiong.


use POSIX qw(strftime);
use URI::Escape;
use Fcntl qw(:DEFAULT :flock :seek);

use FCTranscode;

### Start og main program ###

$ARGV[0] =~ s/"//g;
@subm_remote_id_list = split('&',uri_unescape($ARGV[0]));
write_log($ARGV[0]);

# Reading  collector status file 
# Remember! collector uses ' instead of "

open(FH, "<", $collector_file);	#Handle error. Should not be empty of inexistent
flock FH, LOCK_SH;
@lines = <FH>;
flock FH, LOCK_UN;
close FH;

foreach $line (@lines) {

	$line =~ /remote_id=\'([\w\.\-]+)\'/;
	$remote_id = $1;

	if ($line =~ /jobid=\'([[:xdigit:]-]{36})\'/){
		$jobid = $1; }
	elsif ($line =~ /jobid=\'(\/[\w\/\.]+\.\d+\.status)\'/){
		$jobid = $1; }

        if ($line =~ /batchid=\'([[:xdigit:]-]{36})\'/){
		$batchid = $1; }
	elsif ($line =~ /batchid=\'(n\/a)\'/){
                $batchid = $1; }

	$line =~ /col_status=\'([\w\:\ ]+)\'/;
        $col_status = $1;

	$line =~ /transcoder=\'([^\']+)\'/;
        $transcoder = $1;

	$line =~ /status=\'([\w\:\ ]+)\'/;
        $status = $1;

        $line =~ /percentComplete=\'(\d{1,3})\'/;
        $percomp = $1;

        $line =~ /timeRemaining=\'([\w\(\)\ \.]+)\'/;
        $timerem = $1;

        $line =~ /timeElapsed=\'([\w\(\)\ ]+)\'/;
        $timeelap = $1;

	$line =~ /output=\'([^\']*)\'/;
	$output_file = $1;

        $collector_jobs_status{ $remote_id } = {
		jobid => $jobid,
	        batchid => $batchid,
		col_status => $col_status,
		transcoder => $transcoder,
		status => $status,
                percomp => $percomp,
                timerem => $timerem,
                timeelap => $timeelap,
		output => $output_file,
                }
}


# TODO - IMPORTANT: should change them to output proper error messages

NEXT_SUBM:
foreach $subm_remote_id (@subm_remote_id_list) {

	#$subm_remote_id = uri_unescape($subm_remote_id);

	#print "Remoteid: $subm_remote_id\n";
	foreach $col_key (keys %collector_jobs_status) {
		#print "Col_key: $col_key\n";
		if ($subm_remote_id eq $col_key) {
			#print "Match on $col_key\n transcoder is $collector_jobs_status{$col_key}->{'transcoder'}\n";
			if ( ($collector_jobs_status{$col_key}->{'col_status'} eq 'finished')
			  or ($collector_jobs_status{$col_key}->{'col_status'} eq 'failed'  )) {
				remove_remote_id($col_key);
				print "OK:$col_key\n";
				next NEXT_SUBM;
			}
			else{ # Should send an error bac
				write_log("Received unexpected id for unfinished transcoding for $col_key. This shouldn't have happened.");
				next NEXT_SUBM; }
		}
	}
	# Write a proper error message
	quick_warn("WARN:0000: remote id $subm_remote_id is not in collector status file\n");
}
